package handler

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 请求体结构
// 你可以根据实际需要扩展字段
// 例如装备、物品等
// 这里保持和你的前端/Coze API一致

type CozeStreamRequest struct {
	ConversationID string                   `json:"conversation_id"`
	BotID          string                   `json:"bot_id"`
	UserID         string                   `json:"user_id"`
	Messages       []map[string]interface{} `json:"additional_messages"`
	Parameters     map[string]interface{}   `json:"parameters"`
}

// SSE响应推送
func StreamAdventure(c *gin.Context) {
	var req CozeStreamRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	cozeURL := "https://api.coze.cn/v3/chat?conversation_id=" + req.ConversationID
	payload, _ := json.Marshal(map[string]interface{}{
		"bot_id": req.BotID,
		"user_id": req.UserID,
		"stream": true,
		"additional_messages": req.Messages,
		"parameters": req.Parameters,
	})

	httpReq, _ := http.NewRequestWithContext(context.Background(), "POST", cozeURL, bytes.NewReader(payload))
	httpReq.Header.Set("Authorization", "Bearer <你的APIKey>") // TODO: 替换为你的真实API Key，建议用配置文件管理
	httpReq.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Coze API请求失败"})
		return
	}
	defer resp.Body.Close()

	c.Writer.Header().Set("Content-Type", "text/event-stream")
	c.Writer.Header().Set("Cache-Control", "no-cache")
	c.Writer.Header().Set("Connection", "keep-alive")

	buf := make([]byte, 1024)
	for {
		n, err := resp.Body.Read(buf)
		if n > 0 {
			c.Writer.Write([]byte("data: " + string(buf[:n]) + "\n\n"))
			c.Writer.Flush()
		}
		if err == io.EOF {
			break
		}
		if err != nil {
			break
		}
	}
}
